require 'digest/sha1'

class User < ActiveRecord::Base
  
  has_and_belongs_to_many :roles
  has_many :posts, :dependent => :destroy
  has_many :comments, :dependent => :destroy
  acts_as_voter  
  # restful_auth stuff
  include Authentication
  include Authentication::ByPassword
  include Authentication::ByCookieToken
  include Authorization::StatefulRoles
  
  validates_presence_of     :login
  validates_length_of       :login,    :within => 3..40
  validates_uniqueness_of   :login,    :case_sensitive => false
  validates_format_of       :login,    :with => RE_LOGIN_OK, :message => MSG_LOGIN_BAD

  validates_format_of       :name,     :with => RE_NAME_OK,  :message => MSG_NAME_BAD, :allow_nil => true
  validates_length_of       :name,     :maximum => 100

  validates_presence_of     :email
  validates_length_of       :email,    :within => 6..100 #r@a.wk
  validates_uniqueness_of   :email,    :case_sensitive => false
  validates_format_of       :email,    :with => RE_EMAIL_OK, :message => MSG_EMAIL_BAD

  #validates_inclusion_of    :sex,     :in => %w( true false ), 
                                      #:on => :create, 
                                      #:message => "extension %s is not included in the list"
  attr_accessible :login, :email, :name, :password, :password_confirmation

  def self.authenticate(login, password)
    u = find_in_state :first, :active, :conditions => {:login => login} # need to get the salt
    u && u.authenticated?(password) ? u : nil
  end

  def owns?(object, allowed_roles = ['moderator', 'admin'])
    return true if object.is_a?(User) && object == self
    raise "#{object.class} not respond to user method" unless object.respond_to?(:user)
    raise "#{object.class}.user class is not #{self.class} (got #{object.class.user})" unless object.user.class == self.class

    return true if object.user == self
    allowed_roles.map!(&:downcase)
    return true if roles.any? {|role| allowed_roles.include?(role.title.downcase) }
  end
  
  def sexilize(male, female)
    return sex ? male : female
  end

  protected
    
    def make_activation_code
        self.deleted_at = nil
        self.activation_code = self.class.make_token
    end
end
